package com.zh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zh.common.BaseContext;
import com.zh.entity.ShoppingCart;
import com.zh.mapper.ShoppingCartMapper;
import com.zh.service.ShoppingCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author 你爹
 * @since 2023-09-21
 */
@Service
@Slf4j
@Transactional
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Override
    public ShoppingCart  saveOrAdd(ShoppingCart shoppingCart) {
        shoppingCart.setUserId(BaseContext.getCurrentId());
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        wrapper.eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId());
        wrapper.eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        ShoppingCart cart = this.getOne(wrapper);
        if (cart == null) {
            shoppingCart.setNumber(1);
            this.save(shoppingCart);
            cart=shoppingCart;
            return cart;
        } else {
            log.info("cart:{}", cart);
            cart.setNumber(cart.getNumber() + 1);
            this.updateById(cart);
        }
        return cart;
    }

    @Override
    public ShoppingCart subOrRemove(ShoppingCart shoppingCart) {
        shoppingCart.setUserId(BaseContext.getCurrentId());
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        wrapper.eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId());
        wrapper.eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        ShoppingCart cart = this.getOne(wrapper);
        if(cart.getNumber()>1){
            cart.setNumber(cart.getNumber() - 1);
            this.updateById(cart);
        } else {
            this.removeById(cart.getId());
            cart.setNumber(0);
        }
        return cart;
    }
}
